package com.myproject.config;


import com.myproject.pojo.Users;
import com.myproject.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权doGetAuthorizationInfo");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //给info用户都有的权限
        // info.addStringPermission("user:add");

        //get 对象
        Subject subject = SecurityUtils.getSubject();
        //拿到User对象
        Users currenUser = (Users) subject.getPrincipal();
        //设置当前用户全向
        info.addStringPermission(currenUser.getPerms());

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证doGetAuthenticationInfo");
        //用户名、密码


        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        Users user = userService.queryUserByName(userToken.getUsername());

        if (user == null) {//用户为空
            return null;
        }

        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser", user);
        System.out.println(user.getName() + "\t" + user.getPwd());
        //密码认证shiro去做
        return new SimpleAuthenticationInfo(user, user.getPwd(), "");
    }
}